def TestMessage = ""
def Baseline = "0" 
def VersionInfo = ""
def CustomizeRepos = "" 
def PrCustomizeRepos = ""
def SelectModules = ""
def ExecuteAllModules = ""
def TestNamespace = ""  
def TestPlatform = "all"
def IpInfo = ""
def JobName = ""
def JobId = ""

pipeline { 
    agent { 
        label 'win-node' 
    } 

    options {
        skipDefaultCheckout(true) // 禁止默认拉取代码
    }

    environment { 
        JENKINS_NODE_COOKIE = 'dontKillMe'
        NODE_HOME='D:\\InstallationSoftware\\nodejs'
         
        report_path = '/Users/lizhanwei/automation/db-reports'
        clone_code = '/Users/lizhanwei/automation/scripts/jenkins_clone_code.sh'
        cloud_execute_sql = '/Users/lizhanwei/automation/scripts/jenkins_13dbsql.sh'
        test_code = '/Users/lizhanwei/automation/scripts/jenkins_testcode.sh'
        db_script_tool = '/Users/lizhanwei/automation/scripts/lete-dbscript.jar'
        execute_sql = '/Users/lizhanwei/automation/scripts/jenkins_dbsql.sh'
        test_tool ='/Users/lizhanwei/automation/scripts/jenkins_mobile_testcode.sh'
        cli_build_tool = '/Users/lizhanwei/automation/scripts/jenkins_cli_build.sh'
        harmony_build_tool = '/Users/lizhanwei/automation/scripts/jenkins_harmony_build.sh'
        pipeline_tool = '/Users/lizhanwei/automation/scripts/jenkins_pipeline.sh' 
        leversion_tool = '/Users/lizhanwei/automation/scripts/jenkins_leversion.sh'
        appium_tool = '/Users/lizhanwei/automation/scripts/start-appium.sh'
        backup_screenshot = '/Users/lizhanwei/automation/scripts/backup-screenshot.sh'
        build_code = '/Users/lizhanwei/automation/scripts/jenkins_buildcode.sh'
        adopt_jdk = '/Users/lizhanwei/automation/scripts/adopt-repo-jdk.sh'
        code_path = '/Users/lizhanwei/automation/code'
        public_packs = '/Users/lizhanwei/automation/packs'
        cloud_code_path = '/Users/lizhanwei/automation/code/loongeasy-cloud'
        mobile_code_path = '/Users/lizhanwei/automation/code/loongeasy-cloud-mobile'
        cli_code_path = "/Users/lizhanwei/automation/code/loongeasy-cli"
        ios_code_path = '/Users/lizhanwei/automation/code/loongeasy-native-sdk-ios'
        android_code_path = '/Users/lizhanwei/automation/code/loongeasy-native-sdk-android'
        harmony_code_path = '/Users/lizhanwei/automation/code/loongeasy-native-sdk-harmonyos'
        h5base_code_path = '/Users/lizhanwei/automation/code/loongeasy-h5-base-mobile'
        ios_test_path = '/Users/lizhanwei/automation/code/loongeasy-native-ios'
        harmony_test_path = '/Users/lizhanwei/automation/code/loongeasy-native-harmonyos'
    }

    stages { 
        stage("任务参数检测") { 
            steps { 
                script {  
                    //开始计时
                    StartTime = System.currentTimeMillis()

                    JobName = env.JOB_NAME
                    JobId = env.BUILD_NUMBER
                    echo "JobName: ${JobName}" 
                    echo "BuildNumber: ${JobId}" 

                    //cloud 测试版本
                    VersionInfo = "${loongeasy_cloud}"

                    //测试分支信息统计
                    codeModel = ["loongeasy-bom", "loongeasy-cloud-commons", "loongeasy-commons-encryption-sdk", "loongeasy-commons-service-orchestration", "loongeasy-comm-engine", "loongeasy-service-engine", "loongeasy-commons-i18n", "loongeasy-commons-message-center", "loongeasy-job-scheduler", "loongeasy-cloud", "loongeasy-cloud-mobile", "loongeasy-native-sdk-ios", "loongeasy-native-sdk-android", "loongeasy-native-sdk-harmonyos", "loongeasy-native-js-bridge", "loongeasy-h5-base-mobile","loongeasy-cli"]
                    
                    latestVersion = ["${loongeasy_bom}", "${loongeasy_cloud_commons}", "${loongeasy_commons_encryption_sdk}", "${loongeasy_commons_service_orchestration}", "${loongeasy_comm_engine}", "${loongeasy_service_engine}", "${loongeasy_commons_i18n}", "${loongeasy_commons_message_center}", "${loongeasy_job_scheduler}", "${loongeasy_cloud}", "${loongeasy_cloud_mobile}", "${loongeasy_native_sdk_ios}", "${loongeasy_native_sdk_android}", "${loongeasy_native_sdk_harmonyos}", "${loongeasy_native_js_bridge}", "${loongeasy_h5_base_mobile}", "${loongeasy_cli}"]
                    
                    testParam = ["${loongeasy_bom_pr_branch_name}", "${loongeasy_cloud_commons_pr_branch_name}", "${loongeasy_commons_encryption_sdk_pr_branch_name}", "${loongeasy_commons_i18n_pr_branch_name}", "${loongeasy_commons_message_center_pr_branch_name}", "${loongeasy_commons_service_orchestration_pr_branch_name}", "${loongeasy_comm_engine_pr_branch_name}", "${loongeasy_service_engine_pr_branch_name}", "${loongeasy_job_scheduler_pr_branch_name}", "${loongeasy_cloud_pr_branch_name}", "${loongeasy_cloud_mobile_pr_branch_name}", "${loongeasy_native_sdk_ios_pr_branch_name}", "${loongeasy_native_sdk_android_pr_branch_name}", "${loongeasy_native_sdk_harmonyos_pr_branch_name}", "${loongeasy_native_js_bridge_pr_branch_name}", "${loongeasy_h5_base_mobile_pr_branch_name}", "${loongeasy_cli_pr_branch_name}"]

                    for (int i = 0;i < codeModel.size(); i++){
                        if("${testParam[i]}" != ""){
                            TestMessage+="& ${codeModel[i]} : ${testParam[i]}"
                            
                            if("${codeModel[i]}" == "${pr_repo_name}"){
                                PrCustomizeRepos="${pr_repo_name}=${latestVersion[i]},${testParam[i]}"
                            }
                        }
                    }

                    //更新描述信息 
                    //IpInfo = sh(script:"/sbin/ifconfig |grep '192.168.' |grep -v inet6 |awk '{print \$2}'", returnStdout:true).trim() 
                    wrap([$class: 'BuildUser']){ 
                        buildDescription "Runner=${BUILD_USER} Repo= ${TestMessage}" 
                    }
                    
                    echo "检查是否为PR合并任务"
                    echo "PrId为空，执行回归测试验证任务"
                    Baseline = '1'
                    SelectModules = ""
                    ExecuteAllModules = "true"
                    TestPlatform = "${test_platform}"

                    echo "处理cloud-mobile模块执行案例"
                    SelectModules = ""

                    echo "打印环境变量信息"
                    echo "${PATH}"
                } 
            } 
        } 

        stage("清理测试环境") { 
            steps { 
                script { 
                    echo "删除之前测试Jar包"
                    return
                } 
            } 
        }

        stage("下载平台代码") {
            steps { 
                script {
                    echo "跳过代码下载流程！"
                    return
                } 
            } 
        } 
        
        stage("准备测试依赖") { 
            steps { 
                 script { 
                    echo "下载loongeast-commons-test-dependency模块代码"
                    return
                } 
            } 
        }

        stage("调整jdk版本环境") {
            steps {
                script {
                    echo "切换jdk版本执行"
                }
            }
        } 

        stage("测试环境准备") {
            parallel {
                stage("构建hap") {
                    steps {
                        script {
                            buildHap("pkgDemoApp")
                            buildHap("hkBranchApp")
                        }
                    }
                }

                stage('部署服务'){
                    when {
                        expression {
                            checkRunTest("harmony", "${TestPlatform}")
                        }
                    }
                    
                    steps { 
                        script { 
                            bat """
                            if exist 'D:\\Codes\\harmony\\DSBridge\\target' (
                                rmdir /s /q 'D:\\Codes\\harmony\\DSBridge\\target'
                            )
                            
                            if exist 'D:\\Codes\\harmony\\DSBridge\\src\\test\\java\\target' (
                                rmdir /s /q 'D:\\Codes\\harmony\\DSBridge\\src\\test\\java\\target'
                            )
                            """
                            
                            echo "清理数据库"
                            cleanEnvDb()

                            echo "启动依赖服务"
                            deployEnvService() 

                            return
                        } 
                    } 
                }
            }
        }
        
        stage("运行HARMONY测试") {
            when {
                expression {
                    checkRunTest("harmony", "${TestPlatform}")
                }
            }
            
            steps { 
                script {
                    // 检查端口是否被占用
                    def portInUse = bat(script: 'netstat -ano | findstr :4723', returnStatus: true)
                    if (portInUse == 0) {
                        echo "端口 4723 正在被使用"
                        // 根据需要添加处理逻辑，例如终止进程或退出
                    } else {
                        echo "启动pc appium server服务"
                        bat "start /b appium >appium.log"
                        sleep(time: 10, unit: 'SECONDS')
                    }
                    
                    echo "开始执行harmony自动化测试案例"
                    bat "cd D:\\Codes\\harmony\\DSBridge\\src\\test && mvn clean test -Dplatform=harmony"
                } 
            }
            
            post { 
                always { 
                    script {
                        def testReportDir = "D:\\Codes\\harmony\\DSBridge\\target\\lete-result\\report"
                        def testReportFile = 'le-simple-report.html'
                        def testReportName = "TestReport-HarmonyOS"
                        publishReport(testReportDir, testReportFile, testReportName)
                    } 
                } 
            }
        }
    }

    post {
        always {
            script {
                EndTime = System.currentTimeMillis()
                analyzeExecuteTime(StartTime, EndTime) 
            }
        }
    }  
}

def checkRunTest(name, target) {
    if(target == "all") {
        return true
    }

    if(name == target) {
        return true
    }
}

def publishReport(reportDir, reportFiles, reportName) {
    echo "Upload html report '${reportName}' to jenkins." 
    def reportFile = "${reportDir}/${reportFiles}"
    if(fileExists(reportFile)) {
        publishHTML(target: [ 
            allowMissing: false, 
            alwaysLinkToLastBuild: true, 
            keepAll: true, 
            reportDir: "${reportDir}", 
            reportFiles: "${reportFiles}", 
            reportName: "${reportName}" 
        ])
    } else {
        error("Report [${reportFile}] not found!")
    }
}

//统计job执行时间
def analyzeExecuteTime(start, end) {
    def jobExecuteTime = end - start
    def hours = (jobExecuteTime / (1000 * 60 * 60)) as int
    def minutes = ((jobExecuteTime / (1000 * 60)) as int) % 60
    def seconds = ((jobExecuteTime / 1000) as int) % 60

    echo "任务执行时间：${hours}小时${minutes}分钟${seconds}秒"
}

//清理环境数据库
def cleanEnvDb() {
    try {
        def response = httpRequest(
            url: 'https://test-cloud-mobile.lyzdfintech.com/pipeline/sql/cleanDb',
            httpMode: 'GET',
            acceptType: 'APPLICATION_JSON'
        )
        echo "CleanResult: ${response.content}"
    } catch(Exception e) {
        echo "请求异常: ${e.getMessage()}"
    }
}

//重新部署测试服务
def deployEnvService() {
    def stopResponse = httpRequest(
        url: 'https://test-cloud-mobile.lyzdfintech.com/pipeline/deploy/stop',
        httpMode: 'GET',
    acceptType: 'APPLICATION_JSON'
    )
    echo "StopResult: ${stopResponse.content}"

    def deployResponse = httpRequest(
        url: 'https://test-cloud-mobile.lyzdfintech.com/pipeline/deploy/deploy',
        httpMode: 'GET',
    acceptType: 'APPLICATION_JSON'
    )
    echo "Deploy: ${deployResponse.content}"

    // 初始化参数
    def maxTimeout = 12 * 60 * 1000 // 超时时间 10 分钟（单位：毫秒）
    def pollInterval = 20     // 轮询间隔 20 秒
    def startTime = System.currentTimeMillis() // 开始时间
    def isFinalStatus = false
    def finalStatus = ""
    
    //循环检测
    while (!isFinalStatus && (System.currentTimeMillis() - startTime) < maxTimeout) {
        try {
            // 发送 HTTP 请求
            def response = httpRequest(
                url: 'https://test-cloud-mobile.lyzdfintech.com/pipeline/deploy/check',
                httpMode: 'GET',
                acceptType: 'APPLICATION_JSON'
            )

            // 解析 JSON 响应
            def responseData = response.content
            echo "响应结果: ${responseData}"

            // 判断是否达到最终状态
            if (responseData.contains("Completed")) {
                isFinalStatus = true
                finalStatus = "Completed"
            } else if(responseData.contains("Failed")) {
                isFinalStatus = true
                finalStatus = "Failed"
                echo "任务执行失败,失败原因：${responseData}"
            } else {
                echo "状态未完成，等待 ${pollInterval} 秒后重试..."
                sleep(time: pollInterval, unit: 'SECONDS')
            }
        } catch (Exception e) {
            echo "请求异常: ${e.getMessage()}"
            sleep(time: pollInterval, unit: 'SECONDS') // 异常后等待重试
        }
    }

    // 超时处理
    if (!isFinalStatus) {
        error "检测超时（12 分钟）仍未得到最终状态！"
    }
}

//编译构建hap
def buildHap(appname) {
    rawfile = "D:\\HarmonyWorks\\loongeasy-h5-base-mobile\\platforms\\harmonyos\\entry\\src\\main\\resources\\rawfile"
    happath= "D:\\HarmonyWorks\\loongeasy-h5-base-mobile\\platforms\\harmonyos\\entry\\build\\default\\outputs\\default"
    apppath = "D:\\Mess\\MobileApps\\app"

    echo "编译构建${appname}"

    bat """
    echo '检查判断是否存在rawfile并删除'
    if exist "${rawfile}" (
        rmdir /s /q ${rawfile}
    )

    echo '拷贝rawfile资源文件'
    xcopy /E /I D:\\HarmonyWorks\\app-rawfile\\${appname}\\rawfile ${rawfile}

    echo '编译构建hap'
    cd D:\\HarmonyWorks\\loongeasy-h5-base-mobile\\platforms\\harmonyos
    hvigorw clean && hvigorw --sync && hvigorw --mode module -p product=default assembleHap --parallel --incremental --no-daemon
    """
    
    echo '检查hap编译构建是否成功'
    bat """
    if exist "${happath}\\entry-default-unsigned.hap" (
        echo 'hap编译构建成功'
    ) else (
        echo 'hap编译构建失败'
        exit 1
    )

    echo '重命名并拷贝到app目录下'
    cd ${happath}
    ren entry-default-unsigned.hap ${appname}.hap
    xcopy /Y ${happath}\\${appname}.hap ${apppath}
    """
    
    echo '完成${appname}编译构建'
}